﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace CPPEI.Coolzon.UI
{
    public class NameTextbox : System.Windows.Controls.TextBox
    {
        private System.Windows.Controls.Primitives.Popup _popup;
        public NameTextbox()
        {
            DataObject.AddPastingHandler(this, textBox1_Pasting);
            VerticalAlignment = VerticalAlignment.Center;
            _popup = new System.Windows.Controls.Primitives.Popup();

            StackPanel panel = new StackPanel();
            panel.Orientation = System.Windows.Controls.Orientation.Horizontal;
            panel.HorizontalAlignment = HorizontalAlignment.Stretch;
            panel.VerticalAlignment = VerticalAlignment.Stretch;
            panel.Background = new SolidColorBrush(System.Windows.Media.Colors.Transparent);
            Label txbKeyword = new Label();
            txbKeyword.Content = "名称不能以数字开头或为空或包含空格";
            txbKeyword.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
            txbKeyword.Background = new SolidColorBrush(System.Windows.Media.Colors.Transparent);
            panel.Children.Add(txbKeyword);
            _popup.Child = panel;
            _popup.AllowsTransparency = true;
            _popup.StaysOpen = true;
            _popup.PlacementTarget = this;
            _popup.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
        }
        private void textBox1_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                string text = (string)e.DataObject.GetData(typeof(string));
                string finalText = Text.Insert(SelectionStart, text);

                if (!IsLegal(finalText.First().ToString()))
                { e.CancelCommand(); }
            }
            else { e.CancelCommand(); }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.Key == Key.Space)
                e.Handled = true;
        }

        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            base.OnTextChanged(e);
            TextBox textBox = this as TextBox;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                if (!IsLegal(textBox.Text.First().ToString()))
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);
                }
            }
            else if (change[0].RemovedLength > 0)
            {
                if (!string.IsNullOrWhiteSpace(textBox.Text) && !IsLegal(textBox.Text.First().ToString()))
                {
                    Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render,
                      new Action(() =>
                      {
                          textBox.Undo();
                      }));
                    textBox.Select(offset, 0);
                }
            }
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            if (string.IsNullOrWhiteSpace(Text) || Text.Contains(" "))
            {
                _popup.IsOpen = true;
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render,
                  new Action(() =>
                  {
                      Focus();
                  }));
            }
            else
            {
                _popup.IsOpen = false;
            }
        }

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            base.OnPreviewTextInput(e);
            if (string.IsNullOrWhiteSpace(Text) && !IsLegal(e.Text.First().ToString()))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;

            }
        }

        private bool IsLegal(string firstChar)
        {
            Regex regex = new Regex("^[a-zA-Z\u4e00-\u9fa5_]$");
            if (regex.IsMatch(firstChar))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
